package com.dycong.common.threadUtil;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

/**
 * Created by dycong on 2016/11/16.
 */
public class TestPool {
    // TODO: 2016/11/16 使用开启线程最好使用，Runable/callble-->FutureTask(可省略，加上便于操作)-->Thread/Executors.newFixedThreadPool()-->thread.start()/executorService.submit()
    static String tem="";


    public void test() {

        ThreadPoolService threadPoolService = new ThreadPoolService();
        threadPoolService.submit(() -> testPoll());

        threadPoolService.submit(new Runnable() {
            @Override
            public void run() {
                tem=tem+"OK";
                System.out.println(Thread.currentThread().getName());
            }
        },tem);

        threadPoolService.submit(new Callable<String>() {
            /**
             *Callable的call()方法相当于Runnable的run()方法
             */
            public String call() throws Exception {

                System.out.println(Thread.currentThread().getName());
                return "";
            }

        });

            ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.submit(() -> testPoll());

        executorService.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName());
            }
        });

        executorService.submit(new Callable<String>() {

            public String call() throws Exception {

                System.out.println(Thread.currentThread().getName());
                return "";
            }

        });


    }

    public void future(){
        Callable<Integer>myCallable=new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                System.out.println(Thread.currentThread().getName()+"---testFuture");
                return null;
            }
        };
        Runnable myRunnable=new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName()+"---testFuture-Runnable");
            }
        };
        Thread thread=new Thread(myRunnable);  /*Callable有返回值，Thread不支持有返回值的线程构造，需要用到FutureTask*/
        thread.start();

        FutureTask<Integer>task=new FutureTask<Integer>(myCallable);
        Thread thread1=new Thread(task);
        thread1.start();
        if (task.isDone()){
//            task.get();
        }

    }

    public void testPoll() {
        System.out.println(Thread.currentThread().getName());
    }


}
